package com.hugui.stock.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hugui.stock.configuration.StockApiConfig;
import com.hugui.stock.entity.StockKline;
import com.hugui.stock.entity.StockMarket;
import com.hugui.stock.service.StockApiService;
import com.hugui.stock.util.TencentStockApiUtil;
import com.hugui.stock.util.EastMoneyApiUtil;

/**
 * 股票API服务实现类
 */
@Service
public class StockApiServiceImpl implements StockApiService {
    
    private static final Logger logger = LoggerFactory.getLogger(StockApiServiceImpl.class);
    
    @Autowired
    private StockApiConfig stockApiConfig;
    
    @Override
    public List<StockMarket> getKlineData(String stockCode, String market, String beginDate, String endDate, String days) {
        List<StockMarket> klineData = null;
        
        // 根据配置选择默认API
        if ("tencent".equals(stockApiConfig.getDefaultApi())) {
            klineData = TencentStockApiUtil.getKlineData(stockCode, market, beginDate, endDate, days);
            
            // 如果启用降级且腾讯API失败，尝试东方财富API
            if (stockApiConfig.isEnableFallback() && (klineData == null || klineData.isEmpty())) {
                logger.warn("腾讯API获取股票{}数据失败，尝试使用东方财富API", stockCode);
                klineData = EastMoneyApiUtil.getKlineData(stockCode, market, beginDate, endDate, days);
            }
        } else if ("eastmoney".equals(stockApiConfig.getDefaultApi())) {
            klineData = EastMoneyApiUtil.getKlineData(stockCode, market, beginDate, endDate, days);
            
            // 如果启用降级且东方财富API失败，尝试腾讯API
            if (stockApiConfig.isEnableFallback() && (klineData == null || klineData.isEmpty())) {
                logger.warn("东方财富API获取股票{}数据失败，尝试使用腾讯API", stockCode);
                klineData = TencentStockApiUtil.getKlineData(stockCode, market, beginDate, endDate, days);
            }
        } else {
            // 默认使用腾讯API
            klineData = TencentStockApiUtil.getKlineData(stockCode, market, beginDate, endDate, days);
        }
        
        if (klineData == null || klineData.isEmpty()) {
            logger.error("所有API都无法获取股票{}的数据", stockCode);
        }
        
        return klineData;
    }
    
    @Override
    public StockKline calculateKlineData(List<StockMarket> stockMarketList) {
        if (stockMarketList == null || stockMarketList.isEmpty()) {
            return null;
        }
        
        // 使用腾讯API的计算方法（两个API的计算方法相同）
        return TencentStockApiUtil.calculateKlineData(stockMarketList);
    }
} 